package com.leyou.order.task;

import com.leyou.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class ClearOrderInTime {

    @Autowired
    private OrderService orderService;

    @Autowired
    private RedissonClient redissonClient;

    final long refreshTime = 60000; //每隔1min刷新一次


    @Scheduled(fixedDelay = refreshTime)
    public void clear() {

        //创建锁对象，并制定锁的名称
        RLock lock = redissonClient.getLock("ly-order");

        //获取锁，设置锁自动失效时间为30s
        boolean isLock = lock.tryLock();
        //判断是否获取锁
        if (!isLock){
            //获取失败
            log.info("获取锁失败，停止定时任务");
            return;
        }

        try {
            //执行业务
            log.info("获取锁成功，执行定时任务");
            this.orderService.closeOrderOutOfTime();
            //模拟任务耗时
            Thread.sleep(500);
        } catch (Exception e) {
            log.error("定时清理订单任务执行异常",e);
        } finally {
            //释放锁
            lock.unlock();
            log.info("定时清理订单任务执行完毕，释放锁");
        }
    }
}
